// 导入环境配置
import env from '../config/env';

// 网络请求工具
const request = (url, method = 'GET', data = {}) => {
  // 为请求数据添加tsno时间戳
  const timestamp = Date.now();
  const requestData = {
    ...data,
    tsno: timestamp
  };

  return new Promise((resolve, reject) => {
    wx.request({
      url: env.baseUrl + url,
      method,
      data: requestData,
      header: {
        'Content-Type': 'application/json',
        // 可以在这里添加token等认证信息
        'token': wx.getStorageSync('token') || ''
      },
      timeout: env.timeout,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          reject(new Error(`HTTP Error ${res.statusCode}: ${res.errMsg}`));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

// 封装get请求
const get = (url, data = {}) => {
  return request(url, 'GET', data);
};

// 封装post请求
const post = (url, data = {}) => {
  return request(url, 'POST', data);
};

export default {
  request,
  get,
  post
};
